﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Elentok.Common.Helpers
{
  /// <summary>
  /// Collection-related extension methods
  /// </summary>
  public static class CollectionsHelper
  {
    /// <summary>
    /// Joins all of the given items into one string separated by "<paramref name="separator"/>"
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="items">The items to separate</param>
    /// <param name="separator">The string that separates the items</param>
    /// <param name="convertToString">This method is used to convert each item to string</param>
    /// <returns></returns>
    public static string Join<T>(this IEnumerable<T> items, string separator, Func<T, string> convertToString)
    {
      StringBuilder sb = new StringBuilder();

      bool first = true;
      foreach (T item in items)
      {
        if (first)
          first = false;
        else
          sb.Append(separator);

        sb.Append(convertToString(item));
      }

      return sb.ToString();
    }

    /// <summary>
    /// Gets the value of the given key in the given dictionary
    /// (if the key doesn't exist it will return the default value)
    /// </summary>
    /// <typeparam name="TKey"></typeparam>
    /// <typeparam name="TValue"></typeparam>
    /// <param name="dictionary"></param>
    /// <param name="key"></param>
    /// <param name="defaultValue"></param>
    /// <returns></returns>
    public static TValue GetValue<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue)
    {
      TValue value;
      if (dictionary.TryGetValue(key, out value))
        return value;
      else
        return defaultValue;
    }

    /// <summary>
    /// Converts the given two-dimensional array into a readable string
    /// (each column is separated by a tab (\t) and each row is separated
    /// with a new line).
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="array"></param>
    /// <returns></returns>
    public static string ToReadableString<T>(this T[][] array)
    {
      StringBuilder sb = new StringBuilder();
      for (int row = 0; row < array.Length; row++)
      {
        T[] columnArray = array[row];
        for (int col = 0; col < columnArray.Length; col++)
        {
          sb.Append(array[row][col].ToString());
          sb.Append("\t");
        }
        sb.Append("\r\n");
      }
      return sb.ToString();
    }
  }
}
